#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qmessagebox.h>

#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
  , ui(new Ui::MainWindow)
  , networkManager(new QNetworkAccessManager(this))
  , exchangeRateTimer(new QTimer(this))
{
    ui->setupUi(this);

#if 0
    // 查看当前网络请求支持协议
    QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
    qDebug() << accessManager->supportedSchemes();

    // 检查SSL支持
    qDebug() << "SSL支持:" << QSslSocket::supportsSsl();
    qDebug() << "SSL版本:" << QSslSocket::sslLibraryVersionString();
    qDebug() << "SSL库路径:" << QSslSocket::sslLibraryBuildVersionString();
#endif

    // 初始化网络管理器
    connect(networkManager, &QNetworkAccessManager::finished, this, &MainWindow::onNetworkReply);

    // 设置窗口标题
    this->setWindowTitle("Bark消息推送工具");

    // 初始化UI文本
    ui->pushButton->setText("推送消息");

    // 设置QTextEdit属性
    ui->logEdit->setReadOnly(true);  // 日志框设为只读
    ui->messageEdit->setAcceptRichText(false);  // 消息框不接受富文本


    // 初始化汇率定时器
    connect(exchangeRateTimer, &QTimer::timeout, this, &MainWindow::fetchExchangeRate);
    exchangeRateTimer->start(60000); // 1分钟
    fetchExchangeRate(); // 立即获取一次汇率

    appendLog("应用程序已启动");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QString message = ui->messageEdit->toPlainText().trimmed();
        if (!message.isEmpty()) {
            sendBarkNotification(message);
        } else {
//            appendLog("错误: 消息内容不能为空");
            sendBarkNotification("NULL");
        }
}

void MainWindow::onNetworkReply(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QString url = reply->url().toString();

        QString rawData = QString::fromLocal8Bit(response);

        if (url.contains("api.exchangerate-api.com")) {
            // 处理汇率响应
            QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
            QJsonObject jsonObj = jsonDoc.object();

            if (jsonObj.contains("rates")) {
                QJsonObject rates = jsonObj["rates"].toObject();
                if (rates.contains("CNY")) {
                    double cnyRate = rates["CNY"].toDouble();

                    ui->curr_rate->setText(QString::number(cnyRate));
//                    ui->curr_rate->setText(QString("当前汇率: 1美元 = %1人民币").arg(cnyRate));
                    appendLog(QString("汇率更新成功: 1美元 = %1人民币").arg(cnyRate));

                    checkAndNotifyExchangeRate(cnyRate);
                } else {
                    appendLog("错误: 汇率数据中未找到CNY字段");
                }
            } else {
                appendLog("错误: 汇率数据格式不正确");
            }
        }
        else if (url.contains("https://qt.gtimg.cn/q=hk01810")) {

            qDebug() << rawData;

            // 示例数据："v_hk01810=\"100~小米集团-W~01810~38.800~36.450~38.550~668796750.0~0~0~38.800~0~0~0~0~0~0~0~0~0~3
            QString data = rawData.split('\"')[1]; // 提取引号内的内容
            QStringList fields = data.split('~');
            if(fields.size() >= 30) {
                // 关键字段解析
                QString stockName = fields[1];        // 股票名称
                QString stockCode = fields[2];        // 股票代码
                float currentPrice = fields[3].toFloat();  // 当前价 (第4字段)
                float prevClose = fields[4].toFloat();     // 昨收价 (第5字段)
                float openPrice = fields[5].toFloat();     // 今开价 (第6字段)
                QString updateTime = fields[26];      // 更新时间 (第27字段)
                float change = fields[27].toFloat();  // 涨跌额 (第28字段)
                float changePercent = fields[28].toFloat(); // 涨跌幅% (第29字段)

                // 构造显示文本
                QString infoText = QString("%1 %2\n"
                                          "当前价: %3 HKD\n"
                                          "涨跌: %4 (%5%)\n"
                                          "昨收: %6 HKD | 今开: %7 HKD\n"
                                          "更新时间: %8")
                                  .arg(stockCode, stockName)
                                  .arg(currentPrice, 0, 'f', 3)
                                  .arg(change > 0 ? "+"+QString::number(change, 'f', 3) : QString::number(change, 'f', 3))
                                  .arg(changePercent, 0, 'f', 2)
                                  .arg(prevClose, 0, 'f', 3)
                                  .arg(openPrice, 0, 'f', 3)
                                  .arg(updateTime);

                // 更新UI
                ui->messageEdit->setText(infoText);
                ui->curr_xiaomi->setText(QString::number(currentPrice));

                // 日志记录
                appendLog(QString("小米股价更新 - 当前: %1 | 变动: %2%")
                         .arg(currentPrice, 0, 'f', 3)
                         .arg(changePercent, 0, 'f', 2));

                // 价格波动超过5%触发通知
//                if(qAbs(changePercent) > 5.0) {
//                    QString alertMsg = QString("【小米股价警报】\n"
//                                              "当前价: %1 HKD\n"
//                                              "较昨日: %2% (%3)")
//                                      .arg(currentPrice, 0, 'f', 3)
//                                      .arg(changePercent, 0, 'f', 2)
//                                      .arg(change > 0 ? "上涨" : "下跌");
//                }
            } else {
                appendLog("错误: 小米股票数据字段不足");
            }

        }
        else if (url.contains("api.day.app")) {
            // 处理Bark推送响应
            appendLog("消息推送成功");
            appendLog("服务器响应: " + QString(response));
        }
    } else {
        appendLog(QString("网络错误: %1").arg(reply->errorString()));
    }

    reply->deleteLater();
}

void MainWindow::appendLog(const QString &message)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->logEdit->append("[" + timestamp + "] " + message);  // 使用QTextEdit的append方法
}


void MainWindow::fetchExchangeRate()
{
    QNetworkRequest request(QUrl("https://api.exchangerate-api.com/v4/latest/USD"));
    networkManager->get(request);
    appendLog("正在获取美元兑人民币汇率...");

    QNetworkRequest xiaomiReq(QUrl("https://qt.gtimg.cn/q=hk01810"));
    networkManager->get(xiaomiReq);
    appendLog("正在获取小米当前价...");
}

void MainWindow::checkAndNotifyExchangeRate(double rate)
{
    if (rate > 7.35)
    {
        QString message = QString("汇率上升警报: 1美元 = %1人民币").arg(rate);
        sendBarkNotification(message, true);
    }
    else if (rate <7.25)
    {
        QString message = QString("汇率下跌警报: 1美元 = %1人民币").arg(rate);
        sendBarkNotification(message, true);
    }
}


void MainWindow::sendBarkNotification(const QString &message, bool withSound)
{
    QString barkKey = "Ntoi82spr7hZbNbuC6sJoD";
    QString encodedMessage = QString::fromUtf8(QUrl::toPercentEncoding(message));
    QString url = QString("https://api.day.app/%1/%2").arg(barkKey, encodedMessage);

    if (withSound) {
        url += "?sound=minuet"; // 添加铃声参数
    }

    QNetworkRequest request(url);
    networkManager->get(request);

    appendLog(QString("正在推送消息: %1%2").arg(message, withSound ? " (带铃声)" : ""));
}
